import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user'
import type { LoginParams } from '@/api/user/type'
import { getToken, setToken, removeToken } from '@/utils/token'
import routes from '@/router/routes'
import type { UserState } from './userTypes'

const useUserStore = defineStore('user', {
	// 数据
	state(): UserState {
		return {
			token: getToken('TOKEN') || '',
			routes,
			username: '',
			avatar: '',
		}
	},
	// 方法
	actions: {
		// 登录
		async handlerLogin(formData: LoginParams) {
			const result = await reqLogin(formData)
			if (result.code === 200) {
				this.token = result.data.token as string
				setToken('TOKEN', this.token)
				return 'success'
			} else {
				return Promise.reject(new Error(result.data.message))
			}
		},
		// 获取用户信息
		async getUserInfo() {
			const result = await reqUserInfo()
			if (result.code === 200) {
				this.username = result.data.checkUser!.username
				this.avatar = result.data.checkUser!.avatar
				return 'success'
			} else {
				return Promise.reject(new Error(result.data.message))
			}
		},
		// 退出登录
		logout() {
			// 清除token
			removeToken('TOKEN')
			// 清除用户信息
			this.token = ''
			this.username = ''
			this.avatar = ''
		},
	},
	// 计算属性
	getters: {},
})

export default useUserStore
